//JavaScript Framework 2.0 Code
try {
	Type.registerNamespace('com.yonyou.ncmm_pac_pda.PurchaseInShowPageController');
	com.yonyou.ncmm_pac_pda.PurchaseInShowPageController = function() {
		com.yonyou.ncmm_pac_pda.PurchaseInShowPageController.initializeBase(this);
		this.initialize();
	}
	var listDate;
	var popDialogInfo = {
		"viewid" : "panel17", //显示的控件的id，通常是一个容器控件div
		"popgravity" : "popbottom", //popcenter|poptop|popbottom|popleft|popright,弹出后最终显示的位置
		istouch : 'false'
	};

	function com$yonyou$ncmm_pac_pda$PurchaseInShowPageController$initialize() {
		//you can programing by $ctx API
		//get the context data through $ctx.get()
		//set the context data through $ctx.push(json)
		//set the field of the context through $ctx.put(fieldName, fieldValue)
		//get the parameter of the context through $ctx.param(parameterName)
		//Demo Code:
		//    var str = $ctx.getString();      //获取当前Context对应的字符串
		//    alert($ctx.getString())          //alert当前Context对应的字符串
		//    var json = $ctx.getJSONObject(); //获取当前Context，返回值为json
		//    json["x"] = "a";        //为当前json增加字段
		//    json["y"] = [];           //为当前json增加数组
		//    $ctx.push(json);            //设置context，并自动调用数据绑定
		//
		//    put方法需手动调用databind()
		//    var x = $ctx.get("x");    //获取x字段值
		//    $ctx.put("x", "b");     //设置x字段值
		//    $ctx.put("x", "b");     //设置x字段值
		//    $ctx.databind();            //调用数据绑定才能将修改的字段绑定到控件上
		//    var p1 = $param.getString("p1");   //获取参数p2的值，返回一个字符串
		//    var p2 = $param.getJSONObject("p2");   //获取参数p3的值，返回一个JSON对象
		//    var p3 = $param.getJSONArray("p3");   //获取参数p1的值，返回一个数组

		//your initialize code below...

	}

	function com$yonyou$ncmm_pac_pda$PurchaseInShowPageController$evaljs(js) {
		eval(js)
	}

	/**
	 * 从本地数据库中读取数据
	 */
	function loadListData(sender, args) {

		loadDataFromLocalDB();

	}

	function loadDataFromLocalDB() {
		if (NCMMPubUtil.isTableExist(PurchaseInVO) == false) {
			return;
		}
		NCMMPubUtil.queryVOByConditions(PurchaseInVO, null, function(data) {
		
			if (NCMMPubUtil.isEmpty(data)) {
				$toast("本地没有订单记录！");
				//return;
			}
			data=eval(data);
			//特殊字符处理
			data = NCMMPubUtil.htmlspecialjsonarray2UI(data);
			//$alert("本地data="+$jsonToString(data));
			var jsondata = {
				puinlist : eval(data)
			};
			$ctx.push(jsondata);
		});
		NCMMPubUtil.notifyFilter("search0", "listviewdefine0", ["vbillcode", "materialname"]);
	}

	/*
	 * 初始化表
	 */
	function createTable(sender, args) {

		if ($cache.read("isCreatePuInTable") == "true")
			return;
		NCMMPubUtil.dropTable(PurchaseInVO);
		NCMMPubUtil.createTable(PurchaseInVO);

		$cache.write("isCreatePuInTable", "true");
		NCMMPUINTEST.initTable(PurchaseInVO);
		if ($cache.read("isCreatePuInScaneTable") == "true")
			return;
		NCMMPubUtil.dropTable(PurchaseInScanedVO);
		NCMMPubUtil.createTable(PurchaseInScanedVO);

		$cache.write("isCreatePuInScaneTable", "true");
	}

	/**
	 * 从NC端获取采购到货单数据
	 * 清空本地数据表
	 * 从本地数据库中读取采购到货单数据并显示在页面上
	 */
	function loadData(condition) {
	   //取默认仓库，如果有值，收货仓库为空或等于默认仓库
	   var stordoc = $stringToJSON($cache.read("defaultstordoc"));
	   if(stordoc != null && stordoc != "") {
		   condition["pk_receivestore"] ="in('"+stordoc.pk_stordoc+"','~')";
	   }	   
		var vocount = 0;
		NCMMDBUtil.testNCConnection(function(data) {
			if (data == false || data == "false") {
				$js.hideLoadingBar();
				$toast("下载失败请检查网络设置");
				return;
			} else {
				$app.showLoadingBar({
					msg: "正在下载……"
				});
				//$alert($jsonToString(condition));
				//1. 从NC端获7取档案数据
				NCMMDBUtil.loadNCBaseData(PurchaseInVO, PurchaseInVO, NCMMHttpUtil.BILL, condition, function(data) {
					//如果没有从NC端下载到数据，则本地记录不更新
					//$alert($jsonToString(data));
					if (data == null) {
						$js.hideLoadingBar();
						$toast("没有获取到符合条件的订单");
						return;
					}
					if (data != null && typeof (data) == 'string') {
						$js.hideLoadingBar();
						$toast("下载失败：" + data);
						return;
					}

					//$alert("process data=" + $jsonToString(data));
					// 如果没有信息直接返回
					var billinfos = data.billinfos || {};
					var props = Object.getOwnPropertyNames(billinfos) || [];
					if (props.length == 0) {
						if ($isJSONObject(data)) {
							$js.hideLoadingBar();
							$toast("没有下载到货单");
						} else {
							$js.hideLoadingBar();
							$toast(data);
						}
						return;
					}
					var unUpdateFieldanmes = new Array();
					var numAndUnitJson = {
						num : "nnum",
						cunitid : "cunitid"

					};
					var astnumAndUnitJson = {
						num : "nastnum",
						cunitid : "castunitid"

					};
					vocount = NCMMLOADVOUTIL.updateLocalVosByNC(PurchaseInVO, billinfos, "scanednum", numAndUnitJson, astnumAndUnitJson, unUpdateFieldanmes);
					if (!vocount || vocount < 1) {
						$js.hideLoadingBar();
						$toast("下载的数据为空，请重新检查");
						return 0;
					}

					loadDataFromLocalDB();
					$js.hideLoadingBar();
					$toast("采购到货入库下载了【" + vocount + "】条数据。");

				});
				//3 从本地数据库中读取数据
				return vocount;
			}
		});
	}

	/**
	 * 插入主子表数据
	 */
	function addAggvos(vos) {
		var retCount = 0;
		var billinfos = vos.billinfos;
		rtnvo = [];
		for (var i = 0; i < billinfos.length; i++) {
			var items = billinfos[i].billinfo.items;
			for (var j = 0; j < items.length; j++) {
				var scanednum = {
					"scanednum" : "0"
				};
				//根据单位和辅单位精度处理数量和主数量
				var json = $.extend({}, billinfos[i].billinfo.head, items[j].item, scanednum);

				NCMMPubUtil.insertVO(PurchaseInVO, json);
			}
			retCount++;
		}
		return retCount;
	}

	/**
	 * 插入主子表数据
	 */

	function getPkOrg(condition) {
		var pk_org = NCMMPUINUtil.getDefaultStockPK();
		if (pk_org == null || pk_org == "") {
			return false;
		}
		pk_org = "='" + pk_org + "'";
		condition = $.extend({}, {
			"pk_org" : pk_org
		}, condition);
		return condition;
	}

	/**
	 * 从NC中获取本日采购到货单
	 * @param {Object} sender
	 * @param {Object} args
	 */
	function getDayData(sender, args) {

		var daydate = NCMMDateUtil.getDayDate();
		var dbilldate = "between '" + daydate.beginDate + "' and '" + daydate.endDate + "'";
		var condition = {
			"dbilldate" : dbilldate
		};
		condition = getPkOrg(condition);
		if (condition == false) {
			$toast("下载前请先进行业务设置");
			return;
		}
		loadData(condition);
	}

	/**
	 * 从NC获取本周采购到货单
	 * @param {Object} sender
	 * @param {Object} args
	 */
	function getWeekData(sender, args) {
		var weekDate = NCMMDateUtil.getWeekDate();
		var dbilldate = "between '" + weekDate.beginDate + "' and '" + weekDate.endDate + "'";
		var condition = {
			"dbilldate" : dbilldate
		};
		condition = getPkOrg(condition);
		if (condition == false) {
			$toast("下载前请先进行业务设置");
			return;
		}
		loadData(condition);
	}

	/**
	 * 获取本月采购到货单数据
	 * @param {Object} sender
	 * @param {Object} args
	 */
	function getMonthData(sender, args) {

		var monthDate = NCMMDateUtil.getMonthDate();
		var dbilldate = "between '" + monthDate.beginDate + "' and '" + monthDate.endDate + "'";
		var condition = {
			"dbilldate" : dbilldate
		};
		condition = getPkOrg(condition);
		if (condition == false) {
			$toast("下载前请先进行业务设置");
			return;
		}
		loadData(condition);
	}
	
	//录入单据号
	function scanonchange(sender, args){
	    analysisBillInfo();
	    $ctx.put("code", "");
		$ctx.dataBind();
	}

	function showScanEditPage(sender, args) {
		$scanner.open({
			bindfield : "code",
			callback : "analysisBillInfo()"
		});
	}

	function analysisBillInfo() {
		var json = $ctx.getString("code");
		//1 获取单据码，然后解析出单据号信息，从本地数据库中查找该码对应的单据信息信息赋值
		var condition = {
			"vbillcode" : json
		};
		NCMMPubUtil.queryVOByConditions(PurchaseInVO, condition, function(data) {
			if (NCMMPubUtil.isEmpty(data)||NCMMPubUtil.isEmpty(data[0]["vbillcode"])) {
				$toast("未找到单据码信息，请重新下载单据信息");
				return;
			}
			//处理特殊字符
			data = NCMMPubUtil.htmlspecialjson2UI(data);
			//2 打开扫描记录编辑界面
			var vos = eval(data);

			if (vos.length == 1) {
				var billcode = vos[0]["vbillcode"];
				var billinfo = {
					"vbillcode" : billcode
				};
				$view.open({
					"viewid" : "com.yonyou.ncmm_pac_pda.PurchaseInScanEditPage", //目标页面（首字母大写）全名
					"isKeep" : "true", //打开新页面的同时是否保留当前页面，true为保留，false为不保留
					"billinfo" : billinfo,
				});
			} else if (vos.length > 1) {
				var billcode = vos[0]["vbillcode"];
				var billinfo = {
					"vbillcode" : billcode
				};
				$view.open({
					"viewid" : "com.yonyou.ncmm_pac_pda.PurchaseInScanEditPage", //目标页面（首字母大写）全名
					"isKeep" : "true", //打开新页面的同时是否保留当前页面，true为保留，false为不保留
					"billinfo" : billinfo,
				});
			} else {
				$toast("未找到单据码信息，请重新下载单据信息");
				return;
			}
		});
	}

	function showMenuList(sender, args) {
		NCMMPUINUtil.showMenuLists("imagebutton1");
	}

	function showQueryPage(sender, args) {
		$view.open({
			viewid : "com.yonyou.ncmm_pac_pda.PurchaseQuery",
			isKeep : "true",
			callback : "doQuery()"
		})
	}

	function doQuery() {
		var cdon = $param.getJSONObject("qcondition");
		var json = {};
		json = cdon;
		loadData(json);
	}

	function back(sender, args) {
		$view.close();
	}

	function search(sender, args) {
		NCMMPubUtil.quickFilter();

	}

	/**
	 * 采集按钮
	 */
	function showScanWithRowInfo() {
		$view.closePop(popDialogInfo);
		var row = $id("listviewdefine0").get("row");
		//row = $stringToJSON(row);
		//$alert("row="+$jsonToString(row));
		$view.open({
			viewid : "com.yonyou.ncmm_pac_pda.PurchaseInScanEditPage",
			isKeep : "true",
			showlistrow : row,
			callback : "loadDataFromLocalDB()"
		});

	}

	/**
	 * 详情按钮
	 */
	function showDetail() {
		$view.closePop(popDialogInfo);
		var row = $id("listviewdefine0").get("row");
		//row = $stringToJSON(row);
		//$alert("row="+$jsonToString(row));
		$view.open({
			"viewid" : "com.yonyou.ncmm_pac_pda.PurchaseInDetailPage",
			"isKeep" : "true",
			"row" : row

		})

	}

	/**
	 * 删除按钮
	 */
	function itemDelete(sender, args) {
		$view.closePop(popDialogInfo);
		var params = {
			"title" : "提示",
			"message" : "确定删除所选记录吗？",
			"okbuttontitle" : "确定",
			"cancelbuttontitle" : "取消",
			"style" : "ok-cancel",
			"okaction" : "doDelete()",
			"cancelaction" : "doCancel()"
		};
		$view.openDialog(params);
	}

	function doDelete() {
		var row = $id("listviewdefine0").get("row");
		row = $stringToJSON(row);
		var scanednum = row.scanednum
		if (NCMMPubUtil.isNotEmpty(scanednum) && scanednum != 0) {
			$alert("已扫描数量不为0，不能删除！")
			return;
		}
		NCMMPubUtil.deleteVO(PurchaseInVO, row);
		loadDataFromLocalDB();
	}

	function doCancel() {
		$toast("清除操作已取消。");
	}

	/**
	 * 取消按钮
	 */
	function itemCancle() {
		$view.closePop(popDialogInfo);
	}

	function onEventClick_ListViewItemClick(sender, args) {
		$view.openPop(popDialogInfo);

	}


	com.yonyou.ncmm_pac_pda.PurchaseInShowPageController.prototype = {
		initialize : com$yonyou$ncmm_pac_pda$PurchaseInShowPageController$initialize,
		evaljs : com$yonyou$ncmm_pac_pda$PurchaseInShowPageController$evaljs
	};
	com.yonyou.ncmm_pac_pda.PurchaseInShowPageController.registerClass('com.yonyou.ncmm_pac_pda.PurchaseInShowPageController', UMP.UI.Mvc.Controller);
} catch(e) {
	$e(e);
}